package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.ArrayList;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 创建搜索请求
            SearchRequest request = new SearchRequest("hotel");
            // 构建查询条件
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params, source);
            // 设置分页
            source.from((params.getPage() - 1) * params.getSize());
            source.size(params.getSize());

            //判断location是否有值,如果有值按照距离排序
            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)) {
                source.sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)).
                        order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }


            //执行搜索请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            PageResult pageResult = new PageResult();
            // 设置查询结果数量
            pageResult.setTotal(hits.getTotalHits().value);
            List<HotelDoc> list = new ArrayList<>();
            //遍历文档列表
            for (SearchHit hit : hits) {
                //获取每个文档的source内容(文档json字符串)===>转为   hotelDoc文档java对象
                HotelDoc hotelDoc = JSON.parseObject(hit.getSourceAsString(), HotelDoc.class);
                // 如果有排序字段  获取排序字段中距离的值
                if (StringUtils.isNotBlank(location)) {
                    Object[] sortValues = hit.getSortValues();
                    if (sortValues != null && sortValues.length > 0) {
                        hotelDoc.setDistance(sortValues[0]);
                    }
                }


                list.add(hotelDoc);
            }

            pageResult.setHotels(list);
            return pageResult;
            //解析响应结果
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("es搜索出错了...");
        }


    }


    /**
     * 用于构建查询条件
     *
     * @param params
     * @param source
     */
    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {
        // 构建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(params.getKey())) {
            //如果key为空  查询全部
            source.query(QueryBuilders.matchAllQuery());
        } else {
            //如果key不为空  使用match  查询all字段
            source.query(QueryBuilders.matchQuery("all", params.getKey()));
        }
        //如果城市不为空  使用rwem查询  city字段
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        //如果星际不为空  使用term查询  star字段
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        // 如果品牌不为空  使用term查询  brand字段
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        //  如果价格不为空  使用term查询  price字段
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        // 算分函数条件
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //原始条件查询
                boolQuery,
                //算分函数  数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //算分函数
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //筛选条件(哪些文档需要重新计算得分)
                                QueryBuilders.termQuery("isAD", true),
                                //计算得分的方法   weight直接给一个常量分值
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
                //加权模式: (算分  和  原始得分 如何算计) 默认相乘
        ).boostMode(CombineFunction.MULTIPLY);

        source.query(functionScoreQueryBuilder);


    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            //设置query查询条件
            buildBasicQuery(params, source);
            // 设置size=0
            source.size(0);
            //设置聚合请求条件   brand分组   city分组   starName分组
            buildAggregations(source);
            // 执行聚合搜索请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 获取总和的聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            List<String> cityList = getAggByName(aggregations, "cityAggAgg");
            List<String> starNameList = getAggByName(aggregations, "starNameAgg");
            //将结果封装成 Map<String, List<String>>
            Map<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("city", cityList);
            map.put("starName", starNameList);
            return map;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("聚合查询失败...");
        }

    }


    /**
     * 构建聚合条件
     *
     * @param source
     */
    private void buildAggregations(SearchSourceBuilder source) {
        source.aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20)
        );
        source.aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(20)
        );
        source.aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(20)
        );
    }


    /**
     * @param aggregations 聚合结果对象
     * @param aggName      自定义集合名称
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //  获取指定的聚合结果
        Terms aggResult = aggregations.get(aggName);
        //获取结果中的 buckets 分组信息
        List<? extends Terms.Bucket> buckets = aggResult.getBuckets();
        //遍历分组   得到分组内容
        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 获取每个分组 key  加入到集合
            resultList.add(bucket.getKeyAsString());
        }// 将集合返回
        return resultList;
    }

    /**
     * 实现搜索框自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("自动不全失败....");
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}